package com.dff.jrfw;

import android.Manifest;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.databinding.DataBindingUtil;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.dff.jrfw.common.Constant;
import com.dff.jrfw.databinding.ActivityLoginTwoBinding;
import com.dff.jrfw.model.QueryDeviceInfoModel;
import com.dff.jrfw.remote.CustomCallBack;
import com.dff.jrfw.remote.RetrofitUtilsTwo;
import com.dff.jrfw.utils.DeviceIdUtil;
import com.dff.jrfw.utils.GsonUtils;
import com.dff.jrfw.utils.TimeUtils;
import com.dff.jrfw.utils.ToastUtil;
import com.dff.jrfw.utils.Util;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import cn.com.infosec.mobile.android.IMSSdk;
import cn.com.infosec.mobile.android.managers.CertManager;
import cn.com.infosec.mobile.android.result.Result;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

public class LoginTwoActivity extends BaseActivity implements View.OnClickListener {

    private ActivityLoginTwoBinding binding;
    private OptionsPickerView pickerView;
    private ArrayList<String> accountList = new ArrayList<>();
    private static final int PERMISSON_REQUESTCODE = 1;


    public static void callMe(Context context, ArrayList<String> accountList, boolean clearStack) {
        Intent intent = new Intent(context, LoginTwoActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("accountList", accountList);
        intent.putExtra("clearStack", clearStack);
        context.startActivity(intent);
    }

    public static void callMe(Context context, ArrayList<String> accountList) {
        callMe(context, accountList, false);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_login_two);
        accountList = getIntent().getStringArrayListExtra("accountList");
        initView();
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (getIntent().getBooleanExtra("clearStack", false)) {
            ActivityManager.getInstance().clearStackIfNotTop();
        }
    }


    private void initView() {
        binding.ivInputClear.setOnClickListener(this);
        binding.tvChangeAccount.setOnClickListener(this);
        binding.btnNext.setOnClickListener(this);
        binding.etAccount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String etAccount = charSequence.toString().trim();
                if (etAccount.length() == 0) {
                    binding.tvError.setVisibility(View.INVISIBLE);
                    binding.viewAccountBottomLine.setBackgroundColor(getResources().getColor(R.color.g999999));
                    binding.ivInputClear.setVisibility(View.INVISIBLE);
                } else {
                    binding.ivInputClear.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        binding.etAccount.setText(accountList.get(0));
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_input_clear:
                binding.etAccount.setText("");
                break;
            case R.id.tv_change_account:
                selectAccount();
                break;
            case R.id.btn_next:
                String etAccount = binding.etAccount.getText().toString().trim();
                if (TextUtils.isEmpty(etAccount)) {
                    ToastUtil.toast("请选择登录账号");
                    return;
                }
                Util.hideKeyBoard(binding.etAccount);
                doAccountIsAlive(etAccount);
//                MainActivity.callMe(this);
                break;
        }
    }


    public void selectAccount() {
        if (pickerView == null) {
            pickerView = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    binding.etAccount.setText(accountList.get(options1));
                }
            })
                    .setDividerColor(getResources().getColor(R.color.g999999))
                    .setBgColor(getResources().getColor(R.color.white))
                    .setTextColorCenter(getResources().getColor(R.color.text_black_color))
                    .setCancelColor(getResources().getColor(R.color.g666666))
                    .setSubmitColor(getResources().getColor(R.color.color_base))
                    .setLineSpacingMultiplier(2.0f)
                    .isCenterLabel(true)
                    .setLabels("", "", "")
                    .setTitleColor(getResources().getColor(R.color.text_black_color))
                    .setTitleText("选择登录账号")
                    .build();
            pickerView.setPicker(accountList);
        }
        pickerView.show();
    }


    private void doAccountIsAlive(String username) {
        showLoading();
        RetrofitUtilsTwo.getService().doAccountIsAlive("1", "1", username).enqueue(new CustomCallBack<ResponseBody>() {

            @Override
            public void onFailure(Call call, Throwable t) {
                super.onFailure(call, t);
                hideLoading();
            }

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    binding.tvError.setVisibility(View.INVISIBLE);
                    if (response.body() != null) {
                        String result = response.body().string();
                        JSONObject jsonObject = new JSONObject(result);
                        int code = jsonObject.getInt("code");
                        if (code == 200) {
                            JSONObject data = jsonObject.optJSONObject("data");
                            int isMobile = data.optInt("isMobile");
                            if (isMobile == 3) {
                                binding.tvError.setVisibility(View.INVISIBLE);
                                binding.viewAccountBottomLine.setBackgroundColor(getResources().getColor(R.color.g999999));
                                String mobile = data.optString("mobile");
                                checkCert(username, mobile);
                            } else {
                                hideLoading();
                                binding.tvError.setText("资金账号未激活，请输入正确的账号");
                                binding.tvError.setVisibility(View.VISIBLE);
                                binding.viewAccountBottomLine.setBackgroundColor(getResources().getColor(R.color.red));
                            }
                        } else {
                            hideLoading();
                            String msg = jsonObject.getString("msg");
                            binding.tvError.setText(msg);
                            binding.tvError.setVisibility(View.VISIBLE);
                            binding.viewAccountBottomLine.setBackgroundColor(getResources().getColor(R.color.red));
                        }
                    } else {
                        hideLoading();
                        ResponseBody errorResponseBody = response.errorBody();
                        if (errorResponseBody != null) {
                            ToastUtil.toast(errorResponseBody.string());
                        }
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                    hideLoading();
                }
            }
        });
    }


    private void checkCert(String username, String mobile) {
        CertManager certManager = new CertManager(this);
        boolean certExist = certManager.isCertExist(username);
        if (certExist) {
            certManager.getStatusOnLine(username, new Result.ResultListener() {
                @Override
                public void handleResult(Result result) {
                    String resultID = result.getResultID();
                    if (resultID.equals(Result.STATUS_EFFECTIVE)) {    //证书有效
                        String endTime = certManager.getCertField(username, 7);
                        try {
                            long endTimeLong = TimeUtils.getTimeStamp(endTime);
                            long currentTime = TimeUtils.getCurTimeMills();
                            long restTime = endTimeLong - currentTime;
                            if (restTime > 0) {
                                boolean supportFingerprint = supportFingerprint();
                                if (supportFingerprint) {
                                    queryDeviceInfo(username);
                                } else {
                                    hideLoading();
                                    PsdLoginActivity.callMe(LoginTwoActivity.this, username);
                                }
                            } else {
                                hideLoading();
                                InputCodeActivity.callMe(LoginTwoActivity.this, username, mobile, "loginTwo");
                            }
                        } catch (ParseException e) {
                            hideLoading();
                            e.printStackTrace();
                        }
                    } else {
                        hideLoading();
                        boolean deleteCert = certManager.deleteCert(username);
                        if (deleteCert) {
                            InputCodeActivity.callMe(LoginTwoActivity.this, username, mobile, "loginTwo");
                        } else {
                            ToastUtil.toast("本地证书删除失败");
                        }
                    }
                }
            });
        } else {
            hideLoading();
            LoginActivity.callMe(LoginTwoActivity.this, username);
        }
    }


    // 是否支持指纹
    public boolean supportFingerprint() {
        if (Build.VERSION.SDK_INT < 23) {
//            ToastUtil.toast("您的系统版本过低，不支持指纹功能");
            return false;
        } else {
            KeyguardManager keyguardManager = getSystemService(KeyguardManager.class);
            FingerprintManager fingerprintManager = getSystemService(FingerprintManager.class);
            if (fingerprintManager != null) {
                if (!fingerprintManager.isHardwareDetected()) {
//                    ToastUtil.toast("您的手机不支持指纹功能");
                    return false;
                } else if (keyguardManager != null) {
                    if (!keyguardManager.isKeyguardSecure()) {
//                        ToastUtil.toast("您还未设置锁屏，请先设置锁屏并添加一个指纹");
                        return false;
                    } else if (!fingerprintManager.hasEnrolledFingerprints()) {
//                        ToastUtil.toast("您至少需要在系统设置中添加一个指纹");
                        return false;
                    }
                } else {
//                    ToastUtil.toast("键盘管理初始化失败");
                    return false;
                }
            } else {
//                ToastUtil.toast("指纹管理初始化失败");
                return false;
            }
        }
        return true;
    }


    private void queryDeviceInfo(String username) {
        RetrofitUtilsTwo.getService().doAccountIsAlive("1", "1", username).enqueue(new CustomCallBack<ResponseBody>() {
            @Override
            public void onFailure(Call call, Throwable t) {
                super.onFailure(call, t);
                hideLoading();
            }

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                hideLoading();
                try {
                    if (response.body() != null) {
                        String result = response.body().string();
                        JSONObject jsonObject = new JSONObject(result);
                        int code = jsonObject.getInt("code");
                        if (code == 200) {
                            JSONObject data = jsonObject.optJSONObject("data");
                            String muDevices = data.optString("muDevices");
                            if (!"null".equals(muDevices) && !TextUtils.isEmpty(muDevices)) {
                                List<QueryDeviceInfoModel.MuDevicesDTO> muDevicesDTOS = GsonUtils.jsonToList(muDevices, QueryDeviceInfoModel.MuDevicesDTO.class);
                                String deviceId = DeviceIdUtil.getDeviceId(LoginTwoActivity.this);
                                for (int i = 0; i < muDevicesDTOS.size(); i++) {
                                    if (muDevicesDTOS.get(i).getDeviceId().equals(deviceId)) {
                                        if (muDevicesDTOS.get(i).getFpSwitch() == 1) {         //指纹开关启用
                                            FingerLoginActivity.callMe(LoginTwoActivity.this, username);
                                        } else {
                                            PsdLoginActivity.callMe(LoginTwoActivity.this, username);
                                        }
                                        return;
                                    }
                                }
                            }
                            PsdLoginActivity.callMe(LoginTwoActivity.this, username);
                        } else {
                            String msg = jsonObject.getString("msg");
                            ToastUtil.toast(msg);
                        }
                    } else {
                        ResponseBody errorResponseBody = response.errorBody();
                        if (errorResponseBody != null) {
                            ToastUtil.toast(errorResponseBody.string());
                        }
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}